-- the local upvalues bandwagon
local select = select
local UnitClass = UnitClass
local UnitIsDead = UnitIsDead
local UnitIsGhost = UnitIsGhost
local UnitIsPlayer = UnitIsPlayer
local UnitIsConnected = UnitIsConnected
local RAID_CLASS_COLORS = RAID_CLASS_COLORS
local UnitLevel = UnitLevel
local UnitPowerType = UnitPowerType
local UnitClassification = UnitClassification
local UnitCreatureFamily = UnitCreatureFamily
local UnitCreatureType = UnitCreatureType
local UnitCanAttack = UnitCanAttack
local GetQuestGreenRange = GetQuestGreenRange

local playerClass = select(2, UnitClass("player")) -- combopoints for druid/rogue

local unfiltered = (playerClass == "ROGUE" or playerClass == "WARRIOR")

local backdrop = {
		bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", tile = true, tileSize = 16,
		insets = {left = -1.5, right = -1.5, top = -1.5, bottom = -1.5},
	}
local statusbartexture = "Interface\\AddOns\\oUF_Ammo\\media\\statusbar"
local bordertexture = "Interface\\AddOns\\oUF_Ammo\\media\\border"
	
local white = { r = 1, g = 1, b = 1}

local barFormatMinMax = "%d/%d"
local barFormatPerc = "%.1f%%"
local barFormatPercMinMax = "%.1f%% %d/%d"
local barFormatPercMin = "%.1f%% %d"
local barFormatDeficit = "|cffff8080%d|r"
local barFormatDeficitNoMax = "%d"
local barFormatMinMaxDef = "%d/%d |cffff8080%d|r"

local function fmt_standard(txt, min, max)
	txt:SetFormattedText(barFormatMinMax, min, max)
end

local function fmt_perc(txt, min, max)
	txt:SetFormattedText(barFormatPerc, min/max*100)
end

local function fmt_percmin(txt, min, max)
	txt:SetFormattedText(barFormatPercMin, min/max*100, min)
end

local function fmt_full(txt, min, max)
	local deficit = min - max
	if deficit == 0 then
		txt:SetFormattedText(barFormatMinMax, min, max )
	else
		txt:SetFormattedText(barFormatMinMaxDef, min, max, deficit)
	end
end

local function fmt_deficit(txt, min, max)
	local deficit = min - max
	if deficit < 0 then
		txt:SetFormattedText(barFormatDeficit, deficit)
	else
		txt:SetText(max)
	end
end

local function fmt_deficitnomax(txt, min, max)
	local deficit = min - max
	if deficit < 0 then
		txt:SetFormattedText(barFormatDeficitNoMax, deficit)
	else
		txt:SetText("")
	end
end

local function fmt_percminmax(txt, min, max)
	txt:SetFormattedText(barFormatPercMinMax, min/max*100, min, max)
end

local fmtmeta = { __index = function(self, key)
	if type(key) == "nil" then return nil end
	if not rawget(self, key) then
		rawset(self, key, fmt_standard)
		return self[key]
	end
end}

local formats = setmetatable({}, { 
	__index = function(self, key)
		if type(key) == "nil" then return nil end
		if not rawget(self, key) then
			if key:find("raidpet%d") then self[key] = self.raidpet
			elseif key:find("raidtarget%d") then self[key] = self.raidtarget
			elseif key:find("raid%d") then self[key] = self.raid
			elseif key:find("partypet%d") then self[key] = self.partypet
			elseif key:find("party%dtarget") then self[key] = self.partytarget
			elseif key:find("party%d") then self[key] = self.party
			else
				self[key] = {}
			end
		end
		return self[key]
	end,
	__newindex = function(self, key, value)
		rawset(self, key, setmetatable(value, fmtmeta))
	end,
})

formats.player.health = fmt_full
formats.pet.health = fmt_full
formats.party.health = fmt_full

formats.target.health = fmt_percmin
formats.target.power = fmt_percmin

formats.focus.health = fmt_percmin
formats.focus.power = fmt_percmin

formats.partypet.health = fmt_deficit
formats.partytarget.health = fmt_perc

formats.targettarget.health = fmt_deficit
formats.targettarget.power = fmt_perc

formats.focustarget.health = fmt_deficit
formats.focustarget.power = fmt_perc

formats.raid.health = fmt_deficitnomax

local classificationFormats = {
	worldboss = "%s?? Boss|r",
	rareelite = "%s%d+ Rare|r",
	elite = "%s%d+|r",
	rare = "%s%d Rare|r",
	normal = "%s%d|r",
	trivial = "%s%d|r",
}

local function getDifficultyColor(level)
	local levelDiff = level - UnitLevel("player")
	if levelDiff >= 5 then
		return 1.00, 0.10, 0.10
	elseif levelDiff >= 3 then
		return 1.00, 0.50, 0.25
	elseif levelDiff >= -2 then
		return 1.00, 1.00, 1.00
	elseif -levelDiff <= GetQuestGreenRange() then
		return 0.25, 0.75, 0.25
	end
	return 0.50, 0.50, 0.50
end

-- This is the core of RightClick menus on diffrent frames
local function menu(self)
	local unit = self.unit:sub(1, -2)
	local cunit = self.unit:gsub("(.)", string.upper, 1)

	if(unit == "party" or unit == "partypet") then
		ToggleDropDownMenu(1, nil, _G["PartyMemberFrame"..self.id.."DropDown"], "cursor", 0, 0)
	elseif(_G[cunit.."FrameDropDown"]) then
		ToggleDropDownMenu(1, nil, _G[cunit.."FrameDropDown"], "cursor", 0, 0)
	end
end

oUF.TagEvents["ammmo:level"] = "UNIT_LEVEL PLAYER_LEVEL_UP"
oUF.Tags["ammo:level"] = function( unit ) 
	local level = UnitLevel(unit)
	local fmt = classificationFormats[UnitClassification(unit)] or classificationFormats["normal"]
	local color = UnitCanAttack("player", unit) and Hex(getDifficultyColor(level)) or "|cffffffff"
	return fmt:format( color, level)
end

oUF.TagEvents["ammo:name"] = "UNIT_NAME_UPDATE UNIT_REACTION UNIT_FACTION"
oUF.Tags["ammo:name"] = function( unit ) 
	return UnitName(unit)
end

oUF.TagEvents["ammo:shortname"] = "UNIT_NAME_UPDATE UNIT_REACTION UNIT_FACTION"
oUF.Tags["ammo:shortname"] = function(unit)
	local name = UnitName(unit)
	if name then name = name:sub(1,6) end
	return name
end

oUF.TagEvents["ammo:class"] = "UNIT_NAME_UPDATE"
oUF.Tags["ammo:class"] = function( unit ) 
	local color = white
	local text = UnitCreatureFamily(unit) or UnitCreatureType(unit)
	if UnitIsPlayer(unit) then
		text = UnitClass(unit)
		color = RAID_CLASS_COLORS[select(2, UnitClass(unit))] or white
	end
	return ("%s%s|r"):format( Hex(color), text )
end

oUF.TagEvents["ammo:race"] = "UNIT_NAME_UPDATE"
oUF.Tags["ammo:race"] = function( unit )
	return UnitRace(unit)
end

local function updateHealth(bar, unit, min, max)
	if UnitIsDead(unit) then 
		bar:SetValue(0)
		bar.value:SetText("Dead")
	elseif UnitIsGhost(unit) then
		bar:SetValue(0)
		bar.value:SetText("Ghost")
	elseif not UnitIsConnected(unit) then
		bar:SetValue(0)
		bar.value:SetText("Offline")
	else
		if bar.unitFrame.smallFormat then 
			formats.raid.health(bar.value, min, max)
		else
			formats[unit].health(bar.value, min, max)
		end
	end
end


local function updatePower(bar, unit, min, max)
	if max == 0 or UnitIsDead(unit) or UnitIsGhost(unit) or not UnitIsConnected(unit) then
		bar:SetValue(0)
		if bar.value then
			bar.value:SetText()
		end
	elseif bar.value then
		formats[unit].power(bar.value, min, max)
	end
end

local function noHide(self)
	self:SetVertexColor(.25,.25, .25)
end

local function auraIcon(self, button, icons, index, debuff)
	button.cd:SetReverse()
	button.icon:SetTexCoord(.07, .93, .07, .93) --zoom icon
	button.overlay:SetTexture(bordertexture)
	button.overlay:SetTexCoord(0,1,0,1)
	button.overlay.Hide = noHide
end

local function OnEnter(self)
	self.Name:SetTextColor(1, 0, 1)
	if InCombatLockdown() or self.grid then return end
	UnitFrame_OnEnter(self)
end

local function OnLeave(self)
	self.Name:SetTextColor(1, 1, 1)
	if InCombatLockdown() or self.grid then return end
	UnitFrame_OnLeave()
end

local function getFontString(parent)
	local fs = parent:CreateFontString(nil, "OVERLAY")
	fs:SetFontObject(GameFontNormalSmall)
	fs:SetShadowColor(0,0,0)
	fs:SetShadowOffset(0.8, -0.8)
	fs:SetTextColor(1,1,1)
	fs:SetJustifyH("LEFT")
	return fs
end

local function Banzai(self, unit, aggro)
	if aggro == 1 then
		self.Health.value:SetTextColor(1,0,0)
		if UnitHealth(unit) == UnitHealthMax(unit) then
			self.Health.value:SetText("Aggro")
		end
	else
		self.Health.value:SetTextColor(1,1,1)
	end
end

local function CustomTimeText(self, duration)
	local tformat = "%.1f"
	if self.delay ~= 0 then
		tformat = "%.1f|cffff0000-%.1f|r"
	end
	if self.casting then
		self.Time:SetFormattedText(tformat, self.max - duration, self.delay)
	elseif self.channeling then
		self.Time:SetFormattedText(tformat, duration, self.delay)
	end
end


local function setStyle(settings, self, unit)

	self:SetWidth(settings["initial-width"])
	self:SetHeight(settings["initial-height"])


	self.menu = menu -- Enable the menus
	self:RegisterForClicks("anyup")
	self:SetAttribute("*type2", "menu")
	self:SetScript("OnEnter", OnEnter)
	self:SetScript("OnLeave", OnLeave)

	local tiny = settings["ammo-tiny"]
	local micro = settings["ammo-micro"]
	local grid = settings["ammo-grid"]
	
	local unitInRaid = self:GetParent():GetName():match("oUF_Raid")
	local unitInParty = self:GetParent():GetName():match("oUF_Party")
	
	if grid then
		self.grid = true
	end
	
	local hpheight = 22
	if grid then hpheight = 36
	elseif micro then hpheight = 12
	elseif tiny then hpheight = 16
	end

	local ppheight = 16
	if micro then ppheight = 3 -- same for grid
	elseif tiny then ppheight = 4
	end
	
	-- Background
	self:SetBackdrop(backdrop)
	self:SetBackdropColor(0,0,0,1)

	-- Healthbar
	local hp = CreateFrame("StatusBar", nil, self)
	hp:SetHeight(hpheight)
	hp:SetStatusBarTexture(statusbartexture)
	hp:SetPoint("TOPLEFT")
	hp:SetPoint("TOPRIGHT")
	hp.unitFrame = self
	
	if grid then -- fill from bottom to top
		hp:SetOrientation("VERTICAL")
	end

	-- Healthbar background
	hp.bg = hp:CreateTexture(nil, "BORDER")
	hp.bg:SetAllPoints(hp)
	hp.bg:SetTexture(statusbartexture)
	hp.bg:SetAlpha(.5)
	
	-- healthbar coloring, happy true fest
	hp.colorHappiness = true
	hp.colorClass = true
	hp.colorReaction = true
	hp.colorTapping = true
	
	-- Healthbar text
	hp.value = getFontString(hp)
	if grid then
		hp.value:SetPoint("TOP", 0, -2)
	else
		hp.value:SetPoint("RIGHT", -2, 0)
	end
	
	self.Health = hp
	self.Health.PostUpdate = updateHealth

	local icon = hp:CreateTexture(nil, "OVERLAY")
	icon:SetHeight(16)
	icon:SetWidth(16)
	if grid then
		icon:SetPoint("BOTTOM", self)
	else
		icon:SetPoint("TOP", self, 0, not micro and 8 or 0)
	end
	icon:SetTexture("Interface\\TargetingFrame\\UI-RaidTargetingIcons")
	self.RaidIcon = icon
	
	self.Name = getFontString(hp)
	if grid then
		self.Name:SetPoint("BOTTOMLEFT", 0, 2)
		self.Name:SetPoint("BOTTOMRIGHT", 0, 2)
		self:Tag(self.Name, '[ammo:shortname]')
	else
		self.Name:SetPoint("LEFT", 2, 0)
		self.Name:SetPoint("RIGHT", hp.value, "LEFT", -2, 0)
		self:Tag(self.Name, '[ammo:name]')
	end
	
	-- Power Bar 
	local pp = CreateFrame("StatusBar", nil, self)
	pp:SetHeight(ppheight)
	pp:SetStatusBarTexture(statusbartexture)
	
	pp:SetPoint("LEFT")
	pp:SetPoint("RIGHT")
	pp:SetPoint("TOP", hp, "BOTTOM", 0, not micro and -1.35 or 0)
	
	pp.colorPower = true
	pp.frequentUpdates = true

	pp.bg = pp:CreateTexture(nil, "BORDER")
	pp.bg:SetAllPoints(pp)
	pp.bg:SetTexture(statusbartexture)
	pp.bg:SetAlpha(.5)
	
	self.Power = pp
	self.Power.PostUpdate = updatePower
		
	if not tiny then -- anything larger than tiny has text on the powerbar
		pp.value = getFontString(pp)
		pp.value:SetPoint("RIGHT", -2, 0)
	
		self.Lvl = getFontString(pp)
		self.Lvl:SetPoint("LEFT", pp, "LEFT", 2, 0)
		self:Tag(self.Lvl, '[ammo:level]')

		self.Class = getFontString(pp)
		self.Class:SetPoint("LEFT", self.Lvl, "RIGHT",  1, 0)
		self:Tag(self.Class, '[ammo:class]')
	
		self.Race = getFontString(pp)
		self.Race:SetPoint("LEFT", self.Class, "RIGHT",  1, 0)
		self:Tag(self.Race, '[ammo:race]')
	end

	if unitInParty or unitInraid or unit == "player" then --raid,  party or player gets a leader icon
		local leader = hp:CreateTexture(nil, "OVERLAY")
		leader:SetHeight(16)
		leader:SetWidth(16)
		leader:SetPoint("TOPLEFT", self, -8, 8)
		leader:SetTexture("Interface\\GroupFrame\\UI-Group-LeaderIcon")
		self.Leader = leader
	end
	
	if unit == "player" then -- player gets resting and combat
		local resting = pp:CreateTexture(nil, "OVERLAY")
		resting:SetHeight(16)
		resting:SetWidth(16)
		resting:SetPoint("BOTTOMLEFT", self, -8, -8)
		resting:SetTexture("Interface\\CharacterFrame\\UI-StateIcon")
		resting:SetTexCoord(0.09, 0.43, 0.08, 0.42)
		self.Resting = resting
		local combat = pp:CreateTexture(nil, "OVERLAY")
		combat:SetHeight(16)
		combat:SetWidth(16)
		combat:SetPoint("BOTTOMRIGHT", self, 8, -8)
		combat:SetTexture("Interface\\CharacterFrame\\UI-StateIcon")
		combat:SetTexCoord(0.57, 0.90, 0.08, 0.41)
		self.Combat = combat
	end
	
	if unit == "player" or unit == "target" then -- castbar
		local castbar = CreateFrame("StatusBar", nil, self)
		castbar:SetPoint("TOPRIGHT", self, "BOTTOMRIGHT", 0, -50)
		castbar:SetPoint("TOPLEFT", self, "BOTTOMLEFT", 0, -50)
		castbar:SetStatusBarTexture(statusbartexture)
		castbar:SetStatusBarColor(1, 0.7, 0)
		castbar:SetBackdrop(backdrop)
		castbar:SetBackdropColor(0, 0, 0)
		castbar:SetHeight(22)

		castbar.Text = getFontString(castbar)
		castbar.Text:SetPoint("LEFT", castbar, 2, -1)

		castbar.Time = getFontString(castbar)
		castbar.Time:SetJustifyH("RIGHT")
		castbar.Time:SetPoint("RIGHT", castbar, -2, -1)

		castbar.bg = castbar:CreateTexture(nil, 'BORDER')
		castbar.bg:SetAllPoints(castbar)
		castbar.bg:SetTexture(statusbartexture)
		castbar.bg:SetVertexColor(1, 0.7, 0)
		castbar.bg:SetAlpha(.5)
		
		castbar.Spark = castbar:CreateTexture(nil, "OVERLAY")
		castbar.Spark:SetWidth( 4 )
		castbar.Spark:SetBlendMode("ADD")
		
		castbar.CustomTimeText = CustomTimeText
		castbar.CustomDelayText = CustomTimeText
		
		if unit == "player" then
			castbar.SafeZone = castbar:CreateTexture(nil, 'BORDER')
			castbar.SafeZone:SetTexture(statusbartexture)
			castbar.SafeZone:SetVertexColor(1, 0, 0)
		end
		
		self.Castbar = castbar
	end
	
	-- player, pet party and partypets get debuff highlighting
	if unitInRaid or unitInParty or unit == "player" or unit == "pet" or unit:find("partypet%d") then
		if micro then
			local dbh = hp:CreateTexture(nil, "OVERLAY")
			dbh:SetWidth(16)
			if grid then
				dbh:SetHeight(16)
				dbh:SetPoint("TOPRIGHT", self, "TOPRIGHT")
			else
				dbh:SetPoint("TOPLEFT", self, "TOPRIGHT")
				dbh:SetPoint("BOTTOMLEFT", self, "BOTTOMRIGHT")
			end
			dbh:SetTexture(statusbartexture)
			dbh:SetVertexColor(0,0,0,0) -- set alpha to 0 to hide the texture
			self.DebuffHighlight = dbh
			self.DebuffHighlightAlpha = 1
			self.smallFormat = true
		else
			self.DebuffHighlightBackdrop = true -- oUF_DebuffHighlight Support, using the backdrop
		end
		self.DebuffHighlightFilter = not unfiltered -- only show debuffs I can cure, if I can cure any
	end
	
	if not unit or not unit:find("party%dtarget") then -- party, raid and anything but partytargets get cbft
		self.CombatFeedbackText = getFontString(hp)
		local size = 16
		if grid then size = 12
		elseif micro then size = 14
		end
		self.CombatFeedbackText:SetFont(self.CombatFeedbackText:GetFont(), size, "OUTLINE")
		self.CombatFeedbackText:SetPoint("CENTER", self, "CENTER")
	end
	
	if micro then -- micro units (raid) don't color healthbar but the health text
		self.Banzai = Banzai
	end
	if unit == "focustarget" then
		self.ignoreBanzai = true
	end

	local buffheight = settings["buff-height"] or 16
	local buffwidth = settings["initial-width"]
	buffwidth = buffwidth - (buffwidth%buffheight) -- make sure we have exactly enough room for the buffs
	
	if not unitInParty and not unitInRaid and not unit:find("party%dtarget") and not unit:find("partypet%d") then
		local debuffs = CreateFrame("Frame", nil, self)
		debuffs.size = buffheight
		debuffs:SetHeight(buffheight)
		debuffs:SetWidth(buffwidth)
	
		debuffs:SetPoint("BOTTOMRIGHT", self, "TOPRIGHT",1.5,3)
		debuffs.initialAnchor = "BOTTOMRIGHT"
		debuffs["growth-y"] = "UP"
		debuffs["growth-x"] = "LEFT"
		debuffs.num = 40
		self.Debuffs = debuffs

		local buffs = CreateFrame("Frame", nil, self)
		buffs.size = buffheight
		buffs:SetHeight(buffheight)
		buffs:SetWidth(buffwidth)
		buffs:SetPoint("TOPLEFT", self, "BOTTOMLEFT",-1.5, -3)
		buffs.initialAnchor = "TOPLEFT"
		buffs["growth-y"] = "DOWN"
		buffs.num = 40
		if unit:find("focus") then
			buffs.onlyShowPlayer = true
		end
		self.Buffs = buffs
	end
--[[	elseif not unit and not micro and not tiny then -- this the party but not the raid
		-- no debuffs on my party frames
		local buffs = CreateFrame("Frame", nil, self)
		buffs.size = buffheight
		buffs:SetHeight(buffheight)
		buffs:SetWidth(buffwidth)
		buffs:SetPoint("TOPLEFT", self, "BOTTOMLEFT",-1.5, -3)
		buffs.initialAnchor = "TOPLEFT"
		buffs["growth-y"] = "DOWN"
		buffs.num = floor(buffwidth/buffheight) -- one row of buffs
		buffs.onlyShowPlayer = true
		self.Buffs = buffs
	end
--]]
	if unitInRaid or unitInParty or unit:find("partypet%d") then -- range on party, raid and party pets
		self.Range = {}
		self.Range.insideAlpha = grid and 0.6 or 1.0
		if grid then
			self.Range.outsideAlpha = 0.2
		else
			self.Range.outsideAlpha = micro and 0.4 or 0.6
		end
	end
	
	if unit=="target" then -- and playerClass == "ROGUE" or playerClass == "DRUID" then
		self.cpoints = getFontString(self)
		local font = self.cpoints:GetFont()
		self.cpoints:SetPoint("RIGHT", self, "LEFT", -9, 3)
		self.cpoints:SetFont(font, 38, "OUTLINE")
		self.cpoints:SetJustifyH("RIGHT")
		self:Tag(cpoints, '[cpoints]')
	end
	self.PostCreateAuraIcon = auraIcon
	return self
end

oUF:RegisterStyle("Ammo", setmetatable({
	["initial-width"] = 200,
	["initial-height"] = 39,
	["buff-height"] = 20,
}, {__call = setStyle}))

oUF:RegisterStyle("Ammo_Small", setmetatable({
	["initial-width"] = 150,
	["initial-height"] = 39,
	["ammo-small"] = true,
}, {__call = setStyle}))

oUF:RegisterStyle("Ammo_Tiny", setmetatable({
	["initial-width"] = 125,
	["initial-height"] = 21,
	["ammo-tiny"] = true,
}, {__call = setStyle}))

oUF:RegisterStyle("Ammo_Raid", setmetatable({
	["initial-width"] = 125,
	["initial-height"] = 14,
	["ammo-tiny"] = true,
	["ammo-micro"] = true,
}, {__call = setStyle}))

oUF:RegisterStyle("Ammo_Grid", setmetatable({
	["initial-width"] = 40,
	["initial-height"] = 40,
	["ammo-tiny"] = true,
	["ammo-micro"] = true,
	["ammo-grid"] = true,
}, {__call = setStyle}))

oUF:Factory(function(self)

	self:SetActiveStyle("Ammo")
	local player = self:Spawn("player"):SetPoint("RIGHT", UIParent, "CENTER", -20, -250)
	local target = self:Spawn("target"):SetPoint("LEFT", UIParent, "CENTER", 20, -250)
	local focus = self:Spawn("focus"):SetPoint("LEFT", UIParent, "CENTER", 20, -160)

	self:SetActiveStyle("Ammo_Small")
	local pet = self:Spawn("pet"):SetPoint("RIGHT", UIParent, "CENTER", -245, -250)
	local tot = self:Spawn("targettarget"):SetPoint("LEFT", UIParent, "CENTER", 245, -250)
	local tof = self:Spawn("focustarget"):SetPoint("LEFT", UIParent, "CENTER", 245, -160)

	self:SetActiveStyle("Ammo_Tiny")

	local grid = {}
	self:SetActiveStyle("Ammo_Grid")
	for i = 1, 8 do
		grid[i] = self:SpawnHeader("oUF_Grid"..i, nil, nil, 
			"yOffset", 2.9,
			"groupFilter", tostring(i),
			"showRaid", true,
			"point", "BOTTOM",
			"sortDir", "DESC"
		)
		if i == 1 then
				grid[i]:SetPoint("BOTTOMLEFT", UIParent, "CENTER", 100, 0)
		else
			grid[i]:SetPoint("BOTTOMLEFT", grid[i-1], "BOTTOMRIGHT", 2.9, 0)
		end
		grid[i]:Show()
	end
	
	local partygrid = self:SpawnHeader("oUF_PartyGrid", nil, nil, 
		"yOffset", 2.9,
		"showParty", true,
		"showPlayer", true,
		"point", "BOTTOM",
		"sortDir", "DESC"
	)
	partygrid:SetPoint("BOTTOMLEFT", UIParent, "CENTER", 100, 0)
	partygrid:Show()

	local partyToggle = CreateFrame("Frame")
	partyToggle:RegisterEvent("PLAYER_LOGIN")
	partyToggle:RegisterEvent("RAID_ROSTER_UPDATE")
	partyToggle:RegisterEvent("PARTY_LEADER_CHANGED")
	partyToggle:RegisterEvent("PARTY_MEMBERS_CHANGED")
	partyToggle:SetScript("OnEvent", function(self, event)
		if InCombatLockdown() then self:RegisterEvent("PLAYER_REGEN_ENABLED")
		else
			self:UnregisterEvent("PLAYER_REGEN_ENABLED")
			if GetNumRaidMembers() > 0 then
				partygrid:Hide()
				for i,v in ipairs(grid) do v:Show() end
			else
				partygrid:Show()
				for i,v in ipairs(grid) do v:Hide() end
			end
		end
	end)
	
	local maintanks
	if oRA3 then
		self:SetActiveStyle("Ammo_Tiny")
		maintanks = self:SpawnHeader("oUF_oRAMainTanks", nil, nil,
			"yOffset", 2.9,
			"nameList", table.concat(oRA3:GetSortedTanks(), ","),
			"template", "oUF_AmmoMainTank",
			"showRaid", true,
			"initial-unitWatch", true,
			"point", "BOTTOM",
			"sortDir", "DESC"
		)
		maintanks:SetPoint("BOTTOMLEFT",UIParent, "CENTER", 400, 6)
		local tankhandler = {}
		function tankhandler:OnTanksUpdated(event, tanks) 
			if not InCombatLockdown() then
				maintanks:SetAttribute("nameList", table.concat(tanks, ","))
			end
		end
		oRA3.RegisterCallback(tankhandler, "OnTanksUpdated")
		maintanks:Show()
	end
	

	local swapped = false
	SLASH_OUFAMMO1 = "/oufswap"
	SlashCmdList.OUFAMMO = function()
		if InCombatLockdown() then return end
		swapped = not swapped
		if swapped then
			grid[1]:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 10, 330)
			partygrid:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 10, 330)
			if maintanks then
				maintanks:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 10, 548)
			end
		else
			grid[1]:SetPoint("BOTTOMLEFT", UIParent, "CENTER", 100, 0)
			partygrid:SetPoint("BOTTOMLEFT", UIParent, "CENTER", 100, 0)
			if maintanks then
				maintanks:SetPoint("BOTTOMLEFT",UIParent, "CENTER", 400, 6)
			end
		end
	end
end)



-- move the RuneFrame somewhere sane
RuneFrame:ClearAllPoints()
RuneFrame:SetPoint("CENTER", UIParent, "CENTER", 0, -200)

RuneButtonIndividual1:ClearAllPoints()
RuneButtonIndividual1:SetPoint("CENTER", RuneFrame, "CENTER")

for i=2, 6 do
	_G["RuneButtonIndividual"..i]:ClearAllPoints()
	_G["RuneButtonIndividual"..i]:SetPoint("TOP", _G["RuneButtonIndividual"..(i-1)] , "BOTTOM", 0, -3)
end


